package com.huazhi.wzsnw.util;

import com.mongodb.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
import net.sf.json.JSONObject;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public enum MongoUtil {
    instance;
    private MongoClient mongoClient;

    static {
//        System.out.println("===============MongoDBUtil初始化========================");
//        // 从配置文件中获取属性值
//        String ip = PropertyUtil.getText("mongodbip");
//        int port = 27017;
//        instance.mongoClient = new MongoClient(ip, port);
//        // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
//        // List<ServerAddress> listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018));
//        // instance.mongoClient = new MongoClient(listHost);
//
//        // 大部分用户使用mongodb都在安全内网下，但如果将mongodb设为安全验证模式，就需要在客户端提供用户名和密码：
//        // boolean auth = db.authenticate(myUserName, myPassword);
//        MongoClientOptions.Builder options = new MongoClientOptions.Builder();
//        // options.autoConnectRetry(true);// 自动重连true
//        // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
//        options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100
//        options.connectTimeout(15000);// 连接超时，推荐>3000毫秒
//        options.maxWaitTime(5000); //
//        options.socketTimeout(10000);// 套接字超时时间，0无限制
//        options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数，如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
//        options.writeConcern(WriteConcern.SAFE);//
//        options.build();
    }

    public static final String DBNAME = "AmbientRFID";

    public MongoDatabase getDB(String dbName) {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        return db;
    }

    public MongoCollection<Document> getCollection(String collName) {
        return getDB(DBNAME).getCollection(collName);
    }

    /**
     * 根据表名获取所有的数据
     */
    public List<Document> getTableStructure(String collName) {
        MongoCollection coll = getCollection(collName);
        List<Document> dbList = new ArrayList<Document>();
        for (int i = 1; i < 6; i++) {
            Document query = new Document("state", "1");
            query.put("head", "1");
            query.put("locations", String.valueOf(i));
            Document sort = new Document("oderNumber", 1);
            FindIterable<Document> one = coll.find(query).sort(sort);
            MongoCursor<Document> mongoCursor = one.iterator();
            while (mongoCursor.hasNext()) {
                Document oneDoc = mongoCursor.next();
                if (!"image".equals(oneDoc.get("name"))) {
                    dbList.add(oneDoc);
                }
            }
        }
        return dbList;
    }

    /**
     * 搜索
     */

    public JSONObject search(Integer page, Integer pageSize, List<String> keys, String structureTableName, String mainTableName, String init) {
        Integer index = null;
        if (page != null) {
            index = (page - 1) * pageSize;
        }
        Document finalQuery = makeQuery(keys, structureTableName, init);
        Document sort = new Document();
        sort.put("buyTime", -1);
        Long allCount = getCollection(mainTableName).count(finalQuery);//查询条数
        List<Document> poList = new ArrayList<Document>();
        FindIterable<Document> one = null;

        if (index == null) {
            one = getCollection(mainTableName).find(finalQuery).sort(sort);
        } else {
            one = getCollection(mainTableName).find(finalQuery).sort(sort).skip(index).limit(pageSize);
        }
        MongoCursor<Document> mongoCursor = one.iterator();
        Integer number = 1;
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        List<Document> yesState = getStateColumn(structureTableName);
//        List<Document> timeList = getTimeColumn(structureTableName);

        MongoCollection collBasic = getCollection("mainStructure");
        List<Document> dbList = new ArrayList<Document>();
        FindIterable firstFind = collBasic.find();
        MongoCursor<Document> mongoCursor1 = firstFind.iterator();
        while (mongoCursor1.hasNext()) {
            dbList.add(mongoCursor1.next());
        }
        List<String> timeList0 = new ArrayList<String>();
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy-MM-dd");
        List<String> timeList1 = new ArrayList<String>();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");
        List<String> timeList2 = new ArrayList<String>();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (dbList != null && dbList.size() > 0) {
            for (Document one1 : dbList) {
                if ("datetime".equals(one1.get("type"))) {
                    if ("0".equals(one1.get("dateformat"))) {
                        timeList0.add((String) one1.get("name"));
                    } else if ("1".equals(one1.get("dateformat"))) {
                        timeList1.add((String) one1.get("name"));
                    } else {
                        timeList2.add((String) one1.get("name"));
                    }
                }
            }
        }

        while (mongoCursor.hasNext()) {
            Document oneDc = mongoCursor.next();
            oneDc.put("number", number);
            oneDc.put("id", oneDc.get("_id").toString());
            for (Document oneState : yesState) {
                if (!oneDc.containsKey((String) oneState.get("name"))) {
                    oneDc.put((String) oneState.get("name"), "");
                }
            }

//            for (Document oneTime : timeList) {
//                if (oneDc.containsKey((String) oneTime.get("name"))) {
//                    if (oneDc.get(oneTime.get("name")) != null && !"".equals(oneDc.get(oneTime.get("name")))) {
//                        Object object = oneDc.get(oneTime.get("name"));
//                        Long time = (Long) object;
//                        if (time == 0l) {
//                            oneDc.put((String) oneTime.get("name"), "");
//                        } else {
//                            oneDc.put((String) oneTime.get("name"), sdf1.format(time));
//                        }
//                    } else {
//                        oneDc.put((String) oneTime.get("name"), "");
//                    }
//                }
//            }

            for (String str : timeList0) {
                if (oneDc.containsKey((String) str)) {
                    if (oneDc.get(str) != null && !"".equals(oneDc.get(str))) {
                        Long time = (Long) oneDc.get(str);
                        if (time == 0l) {
                            oneDc.put((String) str, "");
                        } else {
                            oneDc.put((String) str, sdf0.format(time));
                        }
                    }
                } else {
                    oneDc.put((String) str, "");
                }
            }

            for (String str : timeList1) {
                if (oneDc.containsKey((String) str)) {
                    if (oneDc.get(str) != null && !"".equals(oneDc.get(str))) {
                        Long time = (Long) oneDc.get(str);
                        if (time == 0l) {
                            oneDc.put((String) str, "");
                        } else {
                            oneDc.put((String) str, sdf1.format(time));
                        }
                    }
                } else {
                    oneDc.put((String) str, "");
                }
            }

            for (String str : timeList2) {
                if (oneDc.containsKey((String) str)) {
                    if (oneDc.get(str) != null && !"".equals(oneDc.get(str))) {
                        Long time = (Long) oneDc.get(str);
                        if (time == 0l) {
                            oneDc.put((String) str, "");
                        } else {
                            oneDc.put((String) str, sdf2.format(time));
                        }
                    }
                } else {
                    oneDc.put((String) str, "");
                }
            }




            poList.add(oneDc);
            number++;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", allCount);
        jsonObject.put("data", poList);
        return jsonObject;
    }

    //抽象的制造WHERE后面语句的方法
    private Document makeQuery(List<String> keys, String structureTableName, String init) {
        List<Document> canSearchList = getCanSearchColumn(structureTableName);
        List<String> canSearchName = new ArrayList<String>();

        for (Document one : canSearchList) {
            canSearchName.add((String) one.get("name"));
        }
        List<Document> orQueryCombinationList = new ArrayList<Document>();
        for (String oneKey : keys) {
            BasicDBList orQueryList1 = new BasicDBList();
            for (String oneColumn : canSearchName) {
                Pattern pattern;//用在模糊查询得时候，对字段进行匹配
                pattern = Pattern.compile("^.*" + oneKey + ".*$", Pattern.CASE_INSENSITIVE);
                BasicDBObject searchQuery = new BasicDBObject();//条件查询的对象
                searchQuery.put(oneColumn, pattern);
                orQueryList1.add(searchQuery);
            }
            Document orQuery = new Document("$or", orQueryList1);
            orQueryCombinationList.add(orQuery);
        }
        orQueryCombinationList.add(new Document("init", Integer.valueOf(init)));
        Document finalQuery = new Document("$and",
                orQueryCombinationList);
        return finalQuery;
    }

    //拿到可以搜索的列
    public List<Document> getCanSearchColumn(String collName) {
        Document object = new Document();
        object.put("state", "1");
        List<Document> list = new ArrayList<Document>();

        FindIterable<Document> one = getCollection(collName).find(object);
        MongoCursor<Document> mongoCursor = one.iterator();
        while (mongoCursor.hasNext()) {
            Document oneDoc = mongoCursor.next();
            list.add(oneDoc);
        }
        return list;
    }

    //拿到状态时YES的列
    public List<Document> getStateColumn(String collName) {
        BasicDBObject object = new BasicDBObject();
        object.put("state", "1");
        List<Document> list = new ArrayList<Document>();
        MongoCursor<Document> mongoCursor = getCollection(collName).find(object).iterator();
        while (mongoCursor.hasNext()) {
            list.add(mongoCursor.next());
        }
        return list;

    }

    //拿出是时间的列
    public List<Document> getTimeColumn(String collName) {
        BasicDBObject object = new BasicDBObject();
        object.put("type", "datetime");
        List<Document> list = new ArrayList<Document>();
        MongoCursor<Document> mongoCursor = getCollection(collName).find(object).iterator();
        while (mongoCursor.hasNext()) {
            list.add(mongoCursor.next());
        }
        return list;
    }

    //拿到所有列
    public Map<String, List> getStructure(String collName) {
        MongoCollection coll = getCollection(collName);
        Map<String, List> result = new HashMap<String, List>();

        for (int i = 1; i < 6; i++) {
            List<Document> dbList = new ArrayList<Document>();
            Document query = new Document("state", "1");
            query.put("locations", String.valueOf(i));
            Document sort = new Document("oderNumber", 1);
            FindIterable<Document> one = coll.find(query).sort(sort);
            MongoCursor<Document> mongoCursor = one.iterator();
            while (mongoCursor.hasNext()) {
                Document oneDoc = mongoCursor.next();
                oneDoc.put("id", oneDoc.get("_id").toString());
                dbList.add(oneDoc);
            }
            result.put(String.valueOf(i), dbList);
        }
        return result;
    }

    public List<String> getDistinctSelect(String collName, String type) {
        List<String> result = new ArrayList<String>();
        Document bigFilter = new Document();
        Document filter = new Document();
        List<Document> andQueryCombinationList = new ArrayList<Document>();
        filter.put("state", "1");
        filter.put("type", type);


        Document notFilter = new Document("$ne", "operator");
        notFilter.put("$ne", "responsible");
        notFilter.put("$ne", "usePersonnel");
        notFilter.put("$ne", "responsibleDep");
        notFilter.put("$ne", "useDep");
        Document BigNotFilter = new Document("name", notFilter);

        andQueryCombinationList.add(BigNotFilter);
        andQueryCombinationList.add(filter);
        bigFilter.put("$and", andQueryCombinationList);

        FindIterable<Document> one = getCollection(collName).find(bigFilter);
        MongoCursor<Document> mongoCursor = one.iterator();
        while (mongoCursor.hasNext()) {
            Document next = mongoCursor.next();
            result.add((String) next.get("name"));
        }
        return result;
    }

    public List<JSONObject> getSelectsResult(List<String> names, String collName) {
        List<JSONObject> result = new ArrayList<JSONObject>();
        for (String oneName : names) {

            JSONObject oneResult = new JSONObject();
            oneResult.put("name", oneName);
            List<JSONObject> optopns = new ArrayList<JSONObject>();
            Document filter = new Document();
            filter.put("selectName", oneName);

            FindIterable<Document> one = getCollection(collName).find(filter);
            MongoCursor<Document> mongoCursor = one.iterator();


            while (mongoCursor.hasNext()) {
                JSONObject option = new JSONObject();
                Document next = mongoCursor.next();
                option.put("name", (String) next.get("optionName"));
                option.put("value", (String) next.get("optionName"));
                optopns.add(option);
            }

            oneResult.put("data", optopns);
            result.add(oneResult);

        }
        return result;
    }

    public List<JSONObject> getSelectResult(List<String> names, String collName) {
        List<JSONObject> result = new ArrayList<JSONObject>();
        for (String oneName : names) {

            JSONObject oneResult = new JSONObject();
            oneResult.put("name", oneName);
            List<JSONObject> optopns = new ArrayList<JSONObject>();
            Document filter = new Document();
            filter.put("selectName", oneName);

            FindIterable<Document> one = getCollection(collName).find(filter);
            MongoCursor<Document> mongoCursor = one.iterator();
            while (mongoCursor.hasNext()) {
                JSONObject option = new JSONObject();
                Document next = mongoCursor.next();
                option.put("text", (String) next.get("optionName"));
                option.put("value", (String) next.get("optionName"));
                optopns.add(option);
            }

            oneResult.put("value", optopns);
            result.add(oneResult);

        }

        return result;
    }

    //添加一条记录
    public int addData(String collName, Map<String, String> newData) {
        boolean collecionExsit = false;
        MongoCollection collBasic = getCollection("mainStructure");
        MongoCollection coll = getCollection(collName);
        List<Document> dbList = new ArrayList<Document>();
        FindIterable firstFind = collBasic.find();
        MongoCursor<Document> mongoCursor = firstFind.iterator();
        while (mongoCursor.hasNext()) {
            dbList.add(mongoCursor.next());
        }
        Map<String, String> columnStateMap = new HashMap<String, String>();
        Document doc = new Document();
        List<String> timeList0 = new ArrayList<String>();
        List<String> timeList1 = new ArrayList<String>();
        List<String> timeList2 = new ArrayList<String>();

        if (dbList != null && dbList.size() > 0) {
            collecionExsit = true;
            for (Document one : dbList) {
                if ("datetime".equals(one.get("type"))) {
                    if ("0".equals(one.get("dateformat"))) {
                        timeList0.add((String) one.get("name"));
                    } else if ("1".equals(one.get("dateformat"))) {
                        timeList1.add((String) one.get("name"));
                    } else {
                        timeList2.add((String) one.get("name"));
                    }
                }
//                columnStateMap.put((String) one.get("name"), (String) one.get("state"));
            }
        }
        if (collecionExsit && newData != null) {
            for (String one : newData.keySet()) {
                if (timeList0.contains(one)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Long time = 0L;
                    try {
                        time = sdf.parse(newData.get(one)).getTime();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    doc.put(one, time);
                } else if (timeList1.contains(one)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                    Long time = 0L;
                    try {
                        time = sdf.parse(newData.get(one)).getTime();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    doc.put(one, time);
                } else if (timeList2.contains(one)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Long time = 0L;
                    try {
                        time = sdf.parse(newData.get(one)).getTime();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    doc.put(one, time);
                } else {
                    doc.put(one, newData.get(one));
                }
            }
            coll.insertOne(doc);
        }
        return 1;
    }

    //
    public JSONObject getOne(String id, String structureTableName, String collName) {

        List<Document> poList = new ArrayList<Document>();
        List<Document> yesState = getStateColumn(structureTableName);
//        List<Document> timeList = getTimeColumn(structureTableName);
        //获取时间的
        MongoCollection collBasic = getCollection("mainStructure");
        List<Document> dbList = new ArrayList<Document>();
        FindIterable firstFind = collBasic.find();
        MongoCursor<Document> mongoCursor1 = firstFind.iterator();
        while (mongoCursor1.hasNext()) {
            dbList.add(mongoCursor1.next());
        }
        List<String> timeList0 = new ArrayList<String>();
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy-MM-dd");
        List<String> timeList1 = new ArrayList<String>();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");
        List<String> timeList2 = new ArrayList<String>();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (dbList != null && dbList.size() > 0) {
            for (Document one1 : dbList) {
                if ("datetime".equals(one1.get("type"))) {
                    if ("0".equals(one1.get("dateformat"))) {
                        timeList0.add((String) one1.get("name"));
                    } else if ("1".equals(one1.get("dateformat"))) {
                        timeList1.add((String) one1.get("name"));
                    } else {
                        timeList2.add((String) one1.get("name"));
                    }
                }
            }
        }


        Document query = new Document("_id", new ObjectId(id));
        FindIterable<Document> one = getCollection(collName).find(query);
        MongoCursor<Document> mongoCursor = one.iterator();
        while (mongoCursor.hasNext()) {
            Document oneDc = mongoCursor.next();
            oneDc.put("id", oneDc.get("_id").toString());
            for (Document oneState : yesState) {
                if (!oneDc.containsKey((String) oneState.get("name"))) {
                    oneDc.put((String) oneState.get("name"), "");
                }
            }
            for (String str : timeList0) {
                if (oneDc.containsKey((String) str)) {
                    if (oneDc.get(str) != null && !"".equals(oneDc.get(str))) {
                        Long time = (Long) oneDc.get(str);
                        if (time == 0l) {
                            oneDc.put((String) str, "");
                        } else {
                            oneDc.put((String) str, sdf0.format(time));
                        }
                    }
                } else {
                    oneDc.put((String) str, "");
                }
            }

            for (String str : timeList1) {
                if (oneDc.containsKey((String) str)) {
                    if (oneDc.get(str) != null && !"".equals(oneDc.get(str))) {
                        Long time = (Long) oneDc.get(str);
                        if (time == 0l) {
                            oneDc.put((String) str, "");
                        } else {
                            oneDc.put((String) str, sdf1.format(time));
                        }
                    }
                } else {
                    oneDc.put((String) str, "");
                }
            }

            for (String str : timeList2) {
                if (oneDc.containsKey((String) str)) {
                    if (oneDc.get(str) != null && !"".equals(oneDc.get(str))) {
                        Long time = (Long) oneDc.get(str);
                        if (time == 0l) {
                            oneDc.put((String) str, "");
                        } else {
                            oneDc.put((String) str, sdf2.format(time));
                        }
                    }
                } else {
                    oneDc.put((String) str, "");
                }
            }

            poList.add(oneDc);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", 1);
        jsonObject.put("data", poList);
        return jsonObject;
    }

    public int updates(String collName, String structureTableName, Map<String, Object> newData, String tid) {
        boolean collecionExsit = false;
        MongoCollection collBasic = getCollection("mainStructure");
        List<Document> dbList = new ArrayList<Document>();
        FindIterable firstFind = collBasic.find();
        MongoCursor<Document> mongoCursor = firstFind.iterator();
        while (mongoCursor.hasNext()) {
            dbList.add(mongoCursor.next());
        }
        Map<String, String> columnStateMap = new HashMap<String, String>();
        List<String> timeList0 = new ArrayList<String>();
        List<String> timeList1 = new ArrayList<String>();
        List<String> timeList2 = new ArrayList<String>();

        if (dbList != null && dbList.size() > 0) {
            collecionExsit = true;
            for (Document one : dbList) {
                if ("datetime".equals(one.get("type"))) {
                    if ("0".equals(one.get("dateformat"))) {
                        timeList0.add((String) one.get("name"));
                    } else if ("1".equals(one.get("dateformat"))) {
                        timeList1.add((String) one.get("name"));
                    } else {
                        timeList2.add((String) one.get("name"));
                    }
                }
//                columnStateMap.put((String) one.get("name"), (String) one.get("state"));
            }
        }
        if (collecionExsit && newData != null) {
            for (String one : newData.keySet()) {
                if (timeList0.contains(one)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Long time = 0L;
                    try {
                        time = sdf.parse((String) newData.get(one)).getTime();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    newData.put(one, time);
                } else if (timeList1.contains(one)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                    Long time = 0L;
                    try {
                        time = sdf.parse((String) newData.get(one)).getTime();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    newData.put(one, time);
                } else if (timeList2.contains(one)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Long time = 0L;
                    try {
                        time = sdf.parse((String) newData.get(one)).getTime();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    newData.put(one, time);
                } else {
                    newData.put(one, newData.get(one));
                }
            }
            Document object = new Document(newData);
            object.put("lastModifyTime", System.currentTimeMillis());
            Document newObject = new Document();
            newObject.put("$set", object);

            Document query = new Document("_id", new ObjectId(tid));
            FindIterable<Document> one = getCollection(collName).find(query);
            MongoCursor<Document> mongoCursor1 = one.iterator();
            String number="0";
            while (mongoCursor1.hasNext()) {
                Document oneDc = mongoCursor1.next();
                number=oneDc.get("isogeny").toString();
            }

            Document assetNumber = new Document("isogeny", number);
            FindIterable<Document> one1 = getCollection(collName).find(assetNumber);
            MongoCursor<Document> mongoCursor2 = one1.iterator();
            List<String> list=new ArrayList<>();
            while (mongoCursor2.hasNext()) {
                Document oneDc = mongoCursor2.next();
                list.add(oneDc.get("_id").toString());
            }

            for(String s:list){
                Document obj = new Document();
                obj.put("_id", new ObjectId(s));
                UpdateResult updateOneResult = getCollection(collName).updateOne(obj, newObject);
                System.out.println("修改的数量: " + updateOneResult.getModifiedCount());
            }
            return 1;
        }else {
            return 1;
        }


//
//        public int updates(String collName, String structureTableName, Map<String, Object> newData, String tid) {
//            boolean collecionExsit = false;
//            MongoCollection collBasic = getCollection("mainStructure");
//            List<Document> dbList = new ArrayList<Document>();
//            FindIterable firstFind = collBasic.find();
//            MongoCursor<Document> mongoCursor = firstFind.iterator();
//            while (mongoCursor.hasNext()) {
//                dbList.add(mongoCursor.next());
//            }
//            Map<String, String> columnStateMap = new HashMap<String, String>();
//            List<String> timeList0 = new ArrayList<String>();
//            List<String> timeList1 = new ArrayList<String>();
//            List<String> timeList2 = new ArrayList<String>();
//
//            if (dbList != null && dbList.size() > 0) {
//                collecionExsit = true;
//                for (Document one : dbList) {
//                    if ("datetime".equals(one.get("type"))) {
//                        if ("0".equals(one.get("dateformat"))) {
//                            timeList0.add((String) one.get("name"));
//                        } else if ("1".equals(one.get("dateformat"))) {
//                            timeList1.add((String) one.get("name"));
//                        } else {
//                            timeList2.add((String) one.get("name"));
//                        }
//                    }
////                columnStateMap.put((String) one.get("name"), (String) one.get("state"));
//                }
//            }
//            if (collecionExsit && newData != null) {
//                for (String one : newData.keySet()) {
//                    if (timeList0.contains(one)) {
//                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                        Long time = 0L;
//                        try {
//                            time = sdf.parse((String) newData.get(one)).getTime();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        newData.put(one, time);
//                    } else if (timeList1.contains(one)) {
//                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
//                        Long time = 0L;
//                        try {
//                            time = sdf.parse((String) newData.get(one)).getTime();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        newData.put(one, time);
//                    } else if (timeList2.contains(one)) {
//                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        Long time = 0L;
//                        try {
//                            time = sdf.parse((String) newData.get(one)).getTime();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        newData.put(one, time);
//                    } else {
//                        newData.put(one, newData.get(one));
//                    }
//                }
//                Document object = new Document(newData);
//                object.put("lastModifyTime", System.currentTimeMillis());
//                Document newObject = new Document();
//                newObject.put("$set", object);
//
//                Document query = new Document("_id", new ObjectId(tid));
//                FindIterable<Document> one = getCollection(collName).find(query);
//                MongoCursor<Document> mongoCursor1 = one.iterator();
//                String number="0";
//                while (mongoCursor1.hasNext()) {
//                    Document oneDc = mongoCursor1.next();
//                    number=oneDc.get("assetNumber").toString();
//                }
//
//                Document assetNumber = new Document("assetNumber", number);
//                FindIterable<Document> one1 = getCollection(collName).find(assetNumber);
//                MongoCursor<Document> mongoCursor2 = one1.iterator();
//                List<String> list=new ArrayList<>();
//                while (mongoCursor2.hasNext()) {
//                    Document oneDc = mongoCursor2.next();
//                    list.add(oneDc.get("_id").toString());
//                }
//
//                for(String s:list){
//                    Document obj = new Document();
//                    obj.put("_id", new ObjectId(s));
//                    UpdateResult updateOneResult = getCollection(collName).updateOne(obj, newObject);
//                    System.out.println("修改的数量: " + updateOneResult.getModifiedCount());
//                }
//                return 1;
//            }else {
//                return 1;
//            }


//        FindIterable firstFind = getCollection(structureTableName).find(dataTimeQuery);
//        MongoCursor<Document> mongoCursor = firstFind.iterator();
//        while (mongoCursor.hasNext()) {
//            String name = (String) mongoCursor.next().get("name");
//            timeList.add(name);
//        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        for (String one : newData.keySet()) {
//            if (timeList.contains(one)) {
//                try {
//                    String longString = (String)newData.get(one);
//                    Long timeLong = (sdf.parse(longString)).getTime();
//                    newData.put(one,  timeLong);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    return -1;
//                }
//            }
//        }
//        Document object = new Document(newData);
//        object.put("lastModifyTime", System.currentTimeMillis());
//        Document newObject = new Document();
//        newObject.put("$set", object);
//        Document obj = new Document();
//        obj.put("_id", new ObjectId(tid));
//        UpdateResult updateOneResult = getCollection(collName).updateOne(obj, newObject);
//        System.out.println("修改的数量: " + updateOneResult.getModifiedCount());
//        if (updateOneResult.getModifiedCount() > 0) {
//            System.out.println("文档更新一个成功");
//            return 1;
//        } else {
//            System.out.println("文档更新失败");
//            return -1;
//
//       }
    }

    public int update(String collName, String structureTableName, Map<String, Object> newData, String tid) {
        boolean collecionExsit = false;
        MongoCollection collBasic = getCollection("mainStructure");
        List<Document> dbList = new ArrayList<Document>();
        FindIterable firstFind = collBasic.find();
        MongoCursor<Document> mongoCursor = firstFind.iterator();
        while (mongoCursor.hasNext()) {
            dbList.add(mongoCursor.next());
        }
        Map<String, String> columnStateMap = new HashMap<String, String>();
        List<String> timeList0 = new ArrayList<String>();
        List<String> timeList1 = new ArrayList<String>();
        List<String> timeList2 = new ArrayList<String>();

        if (dbList != null && dbList.size() > 0) {
            collecionExsit = true;
            for (Document one : dbList) {
                if ("datetime".equals(one.get("type"))) {
                    if ("0".equals(one.get("dateformat"))) {
                        timeList0.add((String) one.get("name"));
                    } else if ("1".equals(one.get("dateformat"))) {
                        timeList1.add((String) one.get("name"));
                    } else {
                        timeList2.add((String) one.get("name"));
                    }
                }
//                columnStateMap.put((String) one.get("name"), (String) one.get("state"));
            }
        }
        if (collecionExsit && newData != null) {
            for (String one : newData.keySet()) {
                if (timeList0.contains(one)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Long time = 0L;
                    try {
                        time = sdf.parse((String) newData.get(one)).getTime();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    newData.put(one, time);
                } else if (timeList1.contains(one)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                    Long time = 0L;
                    try {
                        time = sdf.parse((String) newData.get(one)).getTime();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    newData.put(one, time);
                } else if (timeList2.contains(one)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Long time = 0L;
                    try {
                        time = sdf.parse((String) newData.get(one)).getTime();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    newData.put(one, time);
                } else {
                    newData.put(one, newData.get(one));
                }
            }
            Document object = new Document(newData);
            object.put("lastModifyTime", System.currentTimeMillis());
            Document newObject = new Document();
            newObject.put("$set", object);
            Document obj = new Document();
            obj.put("_id", new ObjectId(tid));
            UpdateResult updateOneResult = getCollection(collName).updateOne(obj, newObject);
            System.out.println("修改的数量: " + updateOneResult.getModifiedCount());
            if (updateOneResult.getModifiedCount() > 0) {
                System.out.println("文档更新一个成功");
                return 1;
            } else {
                System.out.println("文档更新失败");
                return -1;
            }
        }else {
            return 1;
        }

//        FindIterable firstFind = getCollection(structureTableName).find(dataTimeQuery);
//        MongoCursor<Document> mongoCursor = firstFind.iterator();
//        while (mongoCursor.hasNext()) {
//            String name = (String) mongoCursor.next().get("name");
//            timeList.add(name);
//        }
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        for (String one : newData.keySet()) {
//            if (timeList.contains(one)) {
//                try {
//                    String longString = (String)newData.get(one);
//                    Long timeLong = (sdf.parse(longString)).getTime();
//                    newData.put(one,  timeLong);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    return -1;
//                }
//            }
//        }
//        Document object = new Document(newData);
//        object.put("lastModifyTime", System.currentTimeMillis());
//        Document newObject = new Document();
//        newObject.put("$set", object);
//        Document obj = new Document();
//        obj.put("_id", new ObjectId(tid));
//        UpdateResult updateOneResult = getCollection(collName).updateOne(obj, newObject);
//        System.out.println("修改的数量: " + updateOneResult.getModifiedCount());
//        if (updateOneResult.getModifiedCount() > 0) {
//            System.out.println("文档更新一个成功");
//            return 1;
//        } else {
//            System.out.println("文档更新失败");
//            return -1;
//        }
    }




    //搜索方法
    public JSONObject searchLife(List<String> ids, Integer page, Integer pageSize, List<String> keys, String collName, String type) {
        Integer index = null;
        if (page != null) {
            index = (page - 1) * pageSize;
        }
        Document finalQuery = makeQueryForLife(keys, ids);
        finalQuery.put("type", type);
        Document sort = new Document();
        sort.put("createTime", -1);
        Long allCount = getCollection(collName).count(finalQuery);
        List<Document> poList = new ArrayList<Document>();
        FindIterable<Document> one = null;
        if (index == null) {
            one = getCollection(collName).find(finalQuery).sort(sort);
        } else {
            one = getCollection(collName).find(finalQuery).sort(sort).skip(index).limit(pageSize);
        }
        MongoCursor<Document> mongoCursor = one.iterator();
        Integer number = 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Document> timeList = new ArrayList<Document>();
        timeList.add(new Document("name", "createTime"));
        while (mongoCursor.hasNext()) {
            Document oneDc = mongoCursor.next();
            oneDc.put("number", number);
            oneDc.put("id", oneDc.get("_id").toString());
            for (Document oneTime : timeList) {
                if (oneDc.containsKey((String) oneTime.get("name"))) {
                    if (oneDc.get(oneTime.get("name")) != null && !"".equals(oneDc.get(oneTime.get("name")))) {
                        Long time = (Long) oneDc.get(oneTime.get("name"));
                        if (time != 0) {
                            oneDc.put((String) oneTime.get("name"), sdf.format(time));
                        } else {
                            oneDc.put((String) oneTime.get("name"), "");
                        }
                    } else {
                        oneDc.put((String) oneTime.get("name"), "");
                    }
                }
            }

            poList.add(oneDc);
            number++;
        }


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", allCount);
        jsonObject.put("data", poList);
        return jsonObject;
    }

    //抽象的制造WHERE后面语句的方法
    private Document makeQueryForLife(List<String> keys, List<String> ids) {

        List<String> canSearchName = new ArrayList<String>();
        canSearchName.add("epcCode");
        canSearchName.add("productName");
        canSearchName.add("productPlace");
        canSearchName.add("productResponsible");
        canSearchName.add("productUsePersonnel");
        canSearchName.add("productResponsibleDep");
        canSearchName.add("productUseDep");
        canSearchName.add("operationType");
        canSearchName.add("operator");

        List<Document> orQueryCombinationList = new ArrayList<Document>();
        for (String oneKey : keys) {
            BasicDBList orQueryList1 = new BasicDBList();
            for (String oneColumn : canSearchName) {
                Pattern pattern;//用在模糊查询得时候，对字段进行匹配
                pattern = Pattern.compile("^.*" + oneKey + ".*$", Pattern.CASE_INSENSITIVE);
                BasicDBObject searchQuery = new BasicDBObject();//条件查询的对象
                searchQuery.put(oneColumn, pattern);
                orQueryList1.add(searchQuery);
            }
            Document orQuery = new Document("$or", orQueryList1);
            orQueryCombinationList.add(orQuery);
        }
        if (ids != null) {
            BasicDBList values = new BasicDBList();
            for (String oneKey : ids) {
                values.add(new ObjectId(oneKey));
            }
            orQueryCombinationList.add(new Document("_id", new BasicDBObject("$in", values)));
        }
        Document finalQuery = new Document("$and",
                orQueryCombinationList);
        return finalQuery;
    }

    public JSONObject inspectionListSearch(Integer page, Integer pageSize, List<String> keys, String mainTable) {
        Integer index = null;
        if (page != null) {
            index = (page - 1) * pageSize;
        }
        Document finalQuery = makeQueryInspection(keys);
        Document sort = new Document();
        sort.put("createTime", -1);
        Long allCount = getCollection(mainTable).count(finalQuery);
        List<Document> poList = new ArrayList<Document>();
        FindIterable<Document> one = null;
        if (index == null) {
            one = getCollection(mainTable).find(finalQuery).sort(sort);
        } else {
            one = getCollection(mainTable).find(finalQuery).sort(sort).skip(index).limit(pageSize);
        }
        MongoCursor<Document> mongoCursor = one.iterator();
        Integer number = 1;
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<Document> timeList = new ArrayList<>();
        timeList.add(new Document("name", "createTime"));
        while (mongoCursor.hasNext()) {
            Document oneDc = mongoCursor.next();
            oneDc.put("number", number);
            oneDc.put("id", oneDc.get("_id").toString());
            for (Document oneTime : timeList) {
                if (oneDc.containsKey((String) oneTime.get("name"))) {
                    if (oneDc.get(oneTime.get("name")) != null && !"".equals(oneDc.get(oneTime.get("name")))) {
                        Object object = oneDc.get(oneTime.get("name"));
                        Long time = (Long) object;
                        oneDc.put((String) oneTime.get("name"), sdf1.format(time));
                    } else {
                        oneDc.put((String) oneTime.get("name"), "");
                    }
                }
            }
            poList.add(oneDc);
            number++;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", allCount);
        jsonObject.put("data", poList);
        return jsonObject;
    }

    private Document makeQueryInspection(List<String> keys) {
        List<String> canSearchName = new ArrayList<String>();
        canSearchName.add("inspectionName");
        canSearchName.add("inspectionEpc");
        canSearchName.add("inspectionPerson");
        List<Document> orQueryCombinationList = new ArrayList<Document>();
        for (String oneKey : keys) {
            BasicDBList orQueryList1 = new BasicDBList();
            for (String oneColumn : canSearchName) {
                Pattern pattern;//用在模糊查询得时候，对字段进行匹配
                pattern = Pattern.compile("^.*" + oneKey + ".*$", Pattern.CASE_INSENSITIVE);
                BasicDBObject searchQuery = new BasicDBObject();//条件查询的对象
                searchQuery.put(oneColumn, pattern);
                orQueryList1.add(searchQuery);
            }
            Document orQuery = new Document("$or", orQueryList1);
            orQueryCombinationList.add(orQuery);
        }
        Document finalQuery = new Document("$and",
                orQueryCombinationList);
        return finalQuery;
    }

    public JSONObject getByInspection(String id, String mainTable) {
        Document query = new Document("_id", new ObjectId(id));
        FindIterable<Document> one = getCollection(mainTable).find(query);
        MongoCursor<Document> mongoCursor = one.iterator();
        List<Document> poList = new ArrayList<Document>();
        while (mongoCursor.hasNext()) {
            Document oneDc = mongoCursor.next();
            poList.add(oneDc);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", "1");
        jsonObject.put("data", poList);
        return jsonObject;
    }

}
